﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.UI.YGUI;

namespace com.yoozoo.gta.Extension
{
    public class YScrollRectPreloader : MonoBehaviour
    {
        public List<YTableViewCell> prefabs;
        
        public YScrollRect scrollRect;

        private RectTransform reusableCellContainer;
        private Dictionary<string, YTableViewCell> cellsMap;

        void Start()
        {
            reusableCellContainer = scrollRect.transform.Find("ReusableCells") as RectTransform;
            cellsMap = new Dictionary<string, YTableViewCell>(prefabs.Count);
            for (int i = 0; i < prefabs.Count; ++i)
            {
                YTableViewCell cell = prefabs[i];
                cellsMap[cell.reuseIdentifier] = cell;
            }
        }

        private void OnDestroy()
        {
            scrollRect = null;
            prefabs = null;
            cellsMap = null;
        }

        /// <summary>
        /// 获取缓存池中TableViewCell的数量
        /// </summary>
        /// <param name="reuseIdentifier"></param>
        /// <returns></returns>
        public int GetReusableCellCount(string reuseIdentifier)
        {
            scrollRect.ClearCells();

            int count = 0;
            for (int i = reusableCellContainer.childCount - 1; i >= 0; i--)
            {
                if (reusableCellContainer.GetChild(i).GetComponent<YTableViewCell>().reuseIdentifier == reuseIdentifier)
                {
                    count++;
                }
            }
            return count;
        }
        
        /// <summary>
        /// 提前实例化TableViewCell进缓存池
        /// </summary>
        public void PreInstantiate(int index)
        {
            if (scrollRect==null || prefabs == null || prefabs.Count <= index)
            {
                return;
            }
            
            YTableViewCell nextItem = GameObject.Instantiate(prefabs[index].gameObject, scrollRect.content, false).GetComponent<YTableViewCell>();
            scrollRect.StoreCellForReuse(nextItem);
        }
        public void PreInstantiate(string reuseIdentifier)
        {
            if (scrollRect==null || cellsMap == null)
            {
                return;
            }
            
            YTableViewCell cell = null;
            if (cellsMap.TryGetValue(reuseIdentifier, out cell))
            {
                YTableViewCell nextItem = GameObject.Instantiate(cell.gameObject, scrollRect.content, false).GetComponent<YTableViewCell>();
                scrollRect.StoreCellForReuse(nextItem);
            }
        }
        
    }
    
}